package com.budwk.app.sys.commons.task.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.budwk.app.fetchdata.models.FetchData_emergency;
import com.budwk.app.fetchdata.services.FetchdataEmergencyService;
import com.budwk.app.miniapp.utils.AddressUtils;

import com.budwk.app.miniapp.utils.HttpUtils;
import com.budwk.starter.email.EmailSendServer;
import com.budwk.starter.job.annotation.SJob;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;


import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@IocBean(name = "pullNaturalWarningService",singleton = false)
public class PullNaturalWarningService {


    @Inject
    private FetchdataEmergencyService wxSpiderEmergencyInformationService;

    @Inject
    private EmailSendServer emailSendServer;

    @Inject("taskQueryExecutor")
    private ThreadPoolExecutor taskQueryExecutor;
    @Inject
    private PropertiesProxy propertiesProxy;
    /*
     * 贵州省自然资源厅
     */
     @SJob("emergencyInformation")
    public void emergencyInformation(String taskId, String params) {
        System.out.println("贵州省自然资源厅: "+new Date());
        int pageNumber=1, pageSize=200;
        List<FetchData_emergency> warningBoList = new ArrayList<>();
        while (true) {
            Map<String, Object> params1 = new HashMap<>();
            params1.put("pageNumber", pageNumber);
            params1.put("pageSize", pageSize);
            String result = HttpUtils.getRequest("http://140.210.211.155:8089/datapi/naturalwarning/meteorologicalwarningquery", params1);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject dataJson = jsonObject.getJSONObject("data");
            JSONObject pagerJson = dataJson.getJSONObject("pager");
            int pageCount = pagerJson.getInteger("pageCount");
            if (pageNumber > pageCount) {
                break;
            }
            JSONArray listJson = dataJson.getJSONArray("list");
            JSONArray listJsonNew =  listJson.stream().filter(item->(((JSONObject)item).getString("forecasterword")).indexOf("地质灾害风险较小")<0)
                    .collect(Collectors.toCollection(JSONArray::new));
            if(listJsonNew.isEmpty()) {
                pageNumber++;
                continue;
            }
            for (int i = 0; i < listJsonNew.size(); i++) {
                JSONObject item = listJson.getJSONObject(i);
                String forecasterword =item.getString("forecasterword");
                String[] forecasterwordlist =forecasterword.split(";");
                String informationcontent="";
                String times="";
                if(forecasterword.indexOf("，")>0)
                {
                    times=forecasterword.substring(0,forecasterword.indexOf("，")+1);
                }
                for (int j = 0; j < forecasterwordlist.length; j++) {
                    String title=forecasterwordlist[j];

                    if(title.indexOf("地质灾害")>0)
                    {
                        title=title.substring(title.indexOf("地质灾害"));
                    }

                    String[] information = forecasterwordlist[j].split("、");
                    for (int k = 0; k < information.length; k++) {
                        informationcontent=times;
                        String informationchannels=information[k].replaceAll("我省","");
                        String  district=null;//县
                        if(informationchannels.indexOf("，")>0)
                        {
                            Integer ii =informationchannels.indexOf("，");
                            Integer i2 =informationchannels.length();
                            district=informationchannels.substring(ii+1,i2);
                        }
                        if(district!=null&&district.indexOf("地质灾害")>0)
                        {
                            informationchannels=district.substring(0,district.indexOf("地质灾害"));
                        }
                        district=informationchannels;
                        if(informationchannels!=null&&informationchannels.indexOf("地质灾害")>0)
                        {
                            informationchannels=informationchannels.substring(0,informationchannels.indexOf("地质灾害"));
                        }
                        if(informationchannels!=null&&informationchannels.indexOf("，")>0)
                        {
                            informationchannels=informationchannels.substring(informationchannels.indexOf("，")+1);
                        }
                        informationchannels=informationchannels+title;
                        if(informationchannels!=null&&informationchannels.indexOf("。")>0)
                        {
                            informationchannels=informationchannels.substring(0,informationchannels.indexOf("。"));
                        }
                        informationcontent=informationcontent+informationchannels;
                        FetchData_emergency warningBo = new FetchData_emergency();
                        warningBo.setInformationtitle(informationchannels);//标题
                        warningBo.setReleasetime(((Timestamp) item.getTimestamp("recordtime"))); //发布时间

                        FetchData_emergency vo = wxSpiderEmergencyInformationService.fetch(Cnd.where(FetchData_emergency::getInformationtitle,"=",warningBo.getInformationtitle())
                                .and(FetchData_emergency::getReleasetime,"=",warningBo.getReleasetime()));
                        if (ObjectUtil.isEmpty(vo)) {

                            try {


                                warningBo.setInformationcontent(informationcontent);//内容
                                informationcontent="";
                                if(informationchannels!=null&&informationchannels.indexOf("（")>0&&informationchannels.indexOf("）")>0)
                                {
                                    warningBo.setDisaster_class(informationchannels.substring(informationchannels.indexOf("（")+1,informationchannels.indexOf("）")));
                                }
                                warningBo.setInformationchannels("贵州省自然资源厅");//气象局

                                JSONObject addressInfo = null;
                                JSONObject jsonresult = null;


                                if (district != null) {
                                    ConcurrentHashMap map = new ConcurrentHashMap();
                                    map = AddressUtils.getLatAndLngByAddr(district);
                                    if (map.get("lng") != null && map.get("lat") != null) {
                                        warningBo.setLongitude(String.valueOf(map.get("lng")));
                                        warningBo.setLatitude(String.valueOf(map.get("lat")));
                                        addressInfo = AddressUtils.getAddressInfo(String.valueOf(map.get("lng")), String.valueOf(map.get("lat")));
                                        if (addressInfo != null) {
                                            jsonresult = addressInfo.getJSONObject("result");
                                            if (jsonresult != null) {
                                                JSONObject addressComponent = jsonresult.getJSONObject("addressComponent");
                                                warningBo.setProvince(addressComponent.getString("province"));
                                                String city = addressComponent.getString("city");
                                                city = city.indexOf("省") > 0 ? city.substring(city.indexOf("省") + 1) : city;
                                                warningBo.setCity(city);
                                                warningBo.setDistrict(addressComponent.getString("county"));
                                                warningBo.setDisaster_address(addressComponent.getString("province") + addressComponent.getString("city") + addressComponent.getString("county"));
                                            }
                                        }
                                    }
                                }

                                warningBo.setProvince("贵州省");
                                warningBo.setInformationmedia("贵州省自然资源厅");
                                warningBo.setDisaster_status("灾害");
//                                if(item.getString("event_type")!=null) {
//                                    warningBo.setPicurl(item.getString("event_type")+"_"+item.getString("severity").toUpperCase() + ".png");
//                                }else{
//                                    warningBo.setPicurl("other.png");
//                                }

                                //  warningBo.setEventPicUrl(item.getString("severity"));

                                warningBo.setDisaster_type("地质灾害");
                                //没有类型的再处理
                                warningBo.setPicurl("other.png");
                                warningBo.setAddperson("祥云AI");
                                warningBo.setAddphone("15555555555");
                                //添加人等
                                Date day = new Date();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                warningBo.setAddtime(sdf.format(day));
                                warningBo.setIsshow("0");
                                // emergencyInfoList.add(warningBo);


                                warningBoList.add(warningBo);

                            } catch(Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                }
            }
            pageNumber++;
        }
        if(CollectionUtil.isNotEmpty(warningBoList)){
            wxSpiderEmergencyInformationService.fastInsert(warningBoList);
        }

    }




}
